//
//  BHCommonReportViewController.swift
//  BigHealth
//
//  Created by 蔺百好 on 2021/7/15.
//

import UIKit
import IQKeyboardManagerSwift

class BHCommonReportViewController: BHBaseViewController {
    
    lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout.init()
        let view = UICollectionView.buildCollectionView(layout: layout)
        view.frame = CGRect(x: 0, y: UIScreen.begainY, width: UIScreen.width, height: UIScreen.height-UIScreen.begainY-UIScreen.safeBottomHeight-64)
        view.backgroundColor = .white
        view.delegate = self
        view.dataSource = self
        view.regiseterNib(nibName: "BHCommonReportReasonCell")
        view.regiseterNib(nibName: "BHCommonReportTextCell")
        view.regiseterNib(nibName: "BHCirclePublishImageAddCell")
        view.regiseterNib(nibName: "BHCommonChoseTypeTextCell")

        return view
    }()
    
    
    lazy var reportBtn: UIButton = {
        let btn = UIButton.init(type: .custom)
        btn.frame = CGRect(x: 16, y: UIScreen.height-UIScreen.safeBottomHeight-10-44, width: UIScreen.width-32, height: 44)
        btn.backgroundColor = .color_ADE6D2
        btn.setTitle("提交", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = .systemFont(ofSize: 14, weight: .medium)
        btn.addTarget(self, action: #selector(reportAct), for: .touchUpInside)
        btn.addLayerCorner(22, 0, .white)
        return btn
    }()
    
    // 举报类型 (1-评论  2-动态  3.用户)
    var reportType: Int = 0
    var businessId: String = ""
    
    
    fileprivate var addImageArray: [BHImageOrVideoModel] = []
    fileprivate var reasonArray: [BHCommonDicModel] = []
    
    fileprivate var choseReasonText: String = ""
    fileprivate var contentText: String = ""
    fileprivate var choseImageUrl: [String] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.bh_navigationBar.title_label.text = "举报"
        
        self.view.addSubview(self.collectionView)
        self.view.addSubview(self.reportBtn)
        self.loadReasonService()
    }
    

    @objc func reportAct() {
        if self.choseReasonText.isEmpty == true {
            BHToast.toast(text: "请选择举报类型")
            return
        }
        if self.addImageArray.count != 0 {
            self.uploadReportImageService()
        }else {
            self.reportService()
        }
    }

}


extension BHCommonReportViewController: BHCircleChoseImageOrVideoViewControllerProtocol {
    func didChoseVideoActHandler(videoModel: BHImageOrVideoModel?) {
        
    }
    
    func didChoseImageActHandler(images: [BHImageOrVideoModel]) {
        self.addImageArray = images
    
        self.collectionView.reloadData()
    }
  
}
extension BHCommonReportViewController: UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 4
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if section == 0 || section == 2{
            return 1
        }else if section == 1 {
            return self.reasonArray.count
        }else {
            if self.addImageArray.count < 9 {
                return self.addImageArray.count + 1
            }else {
                return self.addImageArray.count
            }
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if indexPath.section == 0 {
            return CGSize(width: UIScreen.width, height: 53)
        }else if indexPath.section == 1 {
            let wi = (UIScreen.width-32-11)/2.0
            return CGSize(width: wi, height: 34)
        }else if indexPath.section == 2 {
            return CGSize(width: UIScreen.width, height: 180)
        }else {
            let wi = (UIScreen.width-32-10)/3.0
            return CGSize(width: wi-0.5, height: wi)
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        if section == 1 || section == 3{
            return UIEdgeInsets(top: 0, left: 16, bottom: 20, right: 16)
        }else {
            return .zero
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        if section == 1{
            return 20
        }else if section == 3 {
            return 10
        } else {
            return 0
        }
        
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        if section == 1 {
            return 10
        }else if section == 3 {
            return 5
        } else {
            return 0
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("点击：\(indexPath.row)")
        if indexPath.section == 1 {
            let model = self.reasonArray[indexPath.row]
            self.choseReasonText = model.text
            collectionView.reloadData()
            
            self.reportBtn.isSelected = true
            self.reportBtn.backgroundColor = .color_34CE98

        }
        if indexPath.section == 3 {
            if indexPath.row == self.addImageArray.count {
                
                let addSourceVC = BHCircleChoseImageOrVideoViewController.init()
                addSourceVC.choseType = 1
                addSourceVC.entryType = 1
                addSourceVC.delegate = self
                self.navigationController?.pushViewController(addSourceVC, animated: true)
                
            }else { // 预览
                BHMediaTool.showPreview(array: self.addImageArray, current: indexPath.row)
            }
        }
        
    }
}

extension BHCommonReportViewController: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if indexPath.section == 0 {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "BHCommonChoseTypeTextCell", for: indexPath) as! BHCommonChoseTypeTextCell
            return cell
        }else if indexPath.section == 1 {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "BHCommonReportReasonCell", for: indexPath) as! BHCommonReportReasonCell
            let model = self.reasonArray[indexPath.row]
            cell.text_label.text = model.text
            cell.chose = self.choseReasonText == model.text
            return cell
        }else if indexPath.section == 2 {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "BHCommonReportTextCell", for: indexPath) as! BHCommonReportTextCell
            cell.contentText = self.contentText
            cell.textViewDidEndEditingBlock = {[weak self] text in
                self?.contentText = text
            }
            return cell
        }else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "BHCirclePublishImageAddCell", for: indexPath) as! BHCirclePublishImageAddCell
            if indexPath.row < self.addImageArray.count {
                cell.model = self.addImageArray[indexPath.row]
            }else {
                cell.model = nil
            }
            cell.deleteChoseImageBlock = { [weak self] in
                self?.addImageArray.remove(at: indexPath.row)
                self?.collectionView.reloadData()
            }
            return cell
        }
    }
}

extension BHCommonReportViewController {
    func loadReasonService()  {
        SVProgressHUD.show()
        let manager = BHHTTPClient.init()
        manager.get(url: String.common_get_dic_url+"accusation_type", paramters: nil) { (success, errorMsg, responseObject)  in
            SVProgressHUD.dismiss()
            if success == true {
                let result = BHJsonTool.decodeArrayFromDic(dic: responseObject, key: "result")
                
                for dic in result {
                    let model: BHCommonDicModel = BHCommonDicModel.init()
                    model.parseDic(dic as! [String: Any])
                    self.reasonArray.append(model)
                }
                self.collectionView.reloadData()
                
            }else {
                BHToast.toast(text: errorMsg)
              
            }
        }
        
    }
    
    // 上传图片
    func uploadReportImageService()  {
        SVProgressHUD.show()
        let images = BHImageOrVideoModel.transeToImage(array: self.addImageArray)
        let manager = BHHTTPClient.init()
        manager.upload(images: images, progressHandler: nil) { (success, errorMsg, urls) in
            if success == true {
                self.choseImageUrl = urls
                
                self.reportService()
            }else {
                SVProgressHUD.dismiss()
                BHToast.toast(text: errorMsg)
            }
        }
    }
    
    
    // 举报
    func reportService()  {
        BHCommonService.reportService(type: self.reportType, businessId: self.businessId, reportReason: [self.choseReasonText], reportContent: self.contentText, reportImages: self.choseImageUrl) { (success, errorMsg) in
            SVProgressHUD.dismiss()
            if success == true {
                BHToast.toast(text: "内容已提交，请等待工作人员审核")
                DispatchQueue.main.asyncAfter(deadline: .now()+2) {
                    self.navigationController?.popViewController(animated: true)
                }
                
            }else {
                BHToast.toast(text: errorMsg)
            }
        }
    }
}
